package org.dreamwork.jasmine2.util;

import org.dreamwork.jasmine2.javac.IClasspathBuilder;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-4-9
 * Time: 下午6:09
 */
public class WebSphereClasspathBuilder implements IClasspathBuilder {
    public static final String APPLICATION_CLASSPATH_KEY = "com.ibm.websphere.servlet.application.classpath";
    private ServletContext application;
    private Set<URL> urls;

    public WebSphereClasspathBuilder (ServletContext context) {
        this.application = context;
    }

    public String getClasspath () throws IOException {
        String classpath = (String) application.getAttribute (APPLICATION_CLASSPATH_KEY);
        String[] a = classpath.split ("[;:]");
        urls = new HashSet<URL> (a.length);
        Set<String> set = new HashSet<String> ();

        File rt = findJDK ();
        if (rt != null) {
            System.out.println ("find jdk: " + rt);
            urls.add (rt.toURI ().toURL ());
            set.add (rt.getCanonicalPath ());
        }

        boolean isWindows = System.getProperty ("os.name").toLowerCase ().contains ("windows");
        for (String path : a) {
            if (isWindows && path.charAt (0) == '/') path = path.substring (1);
            path = path.replace ("%20", " ");
            File file = new File (path);
            if (!file.exists ()) continue;
            urls.add (file.toURI().toURL ());
            set.add (file.getCanonicalPath ());
        }

        StringBuilder builder = new StringBuilder ();
        for (String path : set) {
            if (builder.length () > 0) builder.append (File.pathSeparatorChar);
            builder.append (path);
        }

        return builder.toString ();
    }

    public Set<URL> getClasspathUrls () throws IOException {
        if (urls == null) getClasspath ();
        return urls;
    }

    private File findJDK () {
        String className = "java/lang/Object.class";
        java.net.URL url = getClass ().getClassLoader ().getResource (className);
        String path = url.getFile ();
        if (path.startsWith ("file:")) path = path.substring (5);
        int pos = path.indexOf ('!');
        path = path.substring (0, pos);
        File file = new File (path);
        return file.exists () ? file : null;
    }
}
